//
//  WlisWebVC.swift
//  Swift_missScarlett
//
//  Created by xmg on 16/8/17.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit
import WebKit
class WlisWebVC: UIViewController {

   /** web视图 */
    @IBOutlet weak var webView: UIView!
    /** 进度条 */
    @IBOutlet weak var progressView: UIProgressView!
    /** webView */
    var wkWebView : WKWebView?
    /** url */
    var url : NSURL?
    
    @IBOutlet weak var back: UIBarButtonItem!
    
    @IBOutlet weak var forward: UIBarButtonItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let webView = WKWebView(frame : self.view.bounds)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        self.wkWebView = webView
        self.webView.addSubview(wkWebView!)
        
//        KVO 
        wkWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
        wkWebView?.addObserver(self, forKeyPath: "title", options: .New, context: nil)
        wkWebView?.addObserver(self, forKeyPath: "canGoBack", options: .New, context: nil)
        wkWebView?.addObserver(self, forKeyPath: "canGoForward", options: .New, context: nil)
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        progressView.progress = Float((self.wkWebView?.estimatedProgress)!)
        progressView.hidden = progressView.progress >= 1
        self.title = self.wkWebView?.title
        
        self.forward.enabled = (self.wkWebView?.canGoForward)!
        self.back.enabled = (self.wkWebView?.canGoBack)!
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        wkWebView?.frame = self.webView.bounds
    }
    
    deinit {
    
        wkWebView?.removeObserver(self, forKeyPath: "estimatedProgress")
        wkWebView?.removeObserver(self, forKeyPath: "title")
        wkWebView?.removeObserver(self, forKeyPath: "canGoForward")
        wkWebView?.removeObserver(self, forKeyPath: "canGoBack")
    }
}

extension WlisWebVC {


    @IBAction func refresh(sender: UIBarButtonItem) {
        self.wkWebView?.reload()
    }
    @IBAction func forward(sender: UIBarButtonItem) {
        self.wkWebView?.goForward()
    }
    @IBAction func back(sender: UIBarButtonItem) {
        
        self.wkWebView?.goBack()
        
    }
    
}